package com.ftg.learn.psi.service.impl;

import com.ftg.learn.psi.Dto.SalesParam;
import com.ftg.learn.psi.entity.PurchaseOrder;
import com.ftg.learn.psi.entity.SalesDetail;
import com.ftg.learn.psi.entity.SalesOrder;
import com.ftg.learn.psi.mapper.ItemMapper;
import com.ftg.learn.psi.mapper.SalesOrderMapper;
import com.ftg.learn.psi.service.ISalesDetailService;
import com.ftg.learn.psi.service.ISalesOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.psi.utils.SnowFlake;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.time.LocalDateTime;

/**
 * <p>
 * 销售订单表 服务实现类
 * </p>
 *
 * @author guoBingTong
 * @since 2022-05-18
 */
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements ISalesOrderService {

    @Autowired
    ISalesDetailService iSalesDetailService;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 添加销售订单表,同时添加销售订单明细表并削减商品的库存。
     * @param salesParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean insertSalesOrder(SalesParam salesParam){

        for (SalesDetail salesDetail : salesParam.getSalesDetailList()){
            if (itemMapper.findOneCount(salesDetail.getItemId()) - salesDetail.getCount() <= 0){
                return false;
            }
        }

        SalesOrder salesOrder = new SalesOrder();
        BeanUtils.copyProperties(salesParam,salesOrder);
        SnowFlake idWorker = new SnowFlake(0, 0);
        long order = idWorker.nextId();
        String orderNo = String.valueOf(order);
        salesOrder.setOrderNo(orderNo);
        salesOrder.setCreateTime(LocalDateTime.now());
        this.save(salesOrder);

        for (SalesDetail salesDetail : salesParam.getSalesDetailList()) {
            salesDetail.setSalesOrderId(salesOrder.getId());
            itemMapper.subCount(salesDetail.getCount(),salesDetail.getItemId());
            iSalesDetailService.save(salesDetail);
        }

        return true;
    }

    /**
     * redisson红锁
     * @param salesParam
     * @return
     */
    @Override
    public boolean suoHaHa(SalesParam salesParam) {
        String key = "lock:shop:" + salesParam.getEmpId();
        RLock lock = redissonClient.getLock(key);
        lock.lock();
        try {
            insertSalesOrder(salesParam);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return true;
    }
}
